
using System;
using UMC.Data;
using UMC.Web;
using UMC.Net;
using System.Security.Cryptography.X509Certificates;

namespace UMC.Proxy;

class SiteCertCheck : UMC.Host.IDoWorker
{
    string Domain, Secret;
    public SiteCertCheck(string domain, string secret)
    {
        this.Domain = domain;
        this.Secret = secret;
    }
    int time = 0;
    void UMC.Host.IDoWorker.DoWork()
    {
        time++;
        Utility.Sign(new Uri(Net.APIProxy.Uri, "Certificater").WebRequest(), this.Secret).Post(new WebMeta().Put("type", "cert", "domain", this.Domain), xhr =>
        {
            if (xhr.StatusCode == System.Net.HttpStatusCode.OK)
            {
                xhr.ReadAsString(str =>
                {
                    var cert = JSON.Deserialize<WebMeta>(str);
                    if (cert.ContainsKey("privateKey"))
                    {
                        var domain = cert["domain"];
                        var privateKey = cert["privateKey"];
                        var publicKey = cert["publicKey"];

                        var x509 = X509Certificate2.CreateFromPem(publicKey, privateKey);

                        UMC.Proxy.Certificater.Certificates[domain] = new UMC.Proxy.Certificater
                        {
                            Name = domain,
                            Certificate = x509
                        };

                        HotCache.Put(new Entities.SiteCert
                        {
                            Domain = domain,
                            ExpirationTime = Utility.TimeSpan(x509.NotAfter),
                            CheckTime = Utility.TimeSpan(),
                            PrivateKey = privateKey,
                            PublicKey = publicKey,
                            IsApiumc = false
                        });
                    }
                    else if (time < 10)
                    {
                        HttpMimeServier.Register(30, this);

                    }
                });
            }
            else
            {
                xhr.ReadAsData((b, ch, l) => { }); ;
                if (time < 10)
                {
                    HttpMimeServier.Register(30, this);
                }
            }
        });
    }

}

